const account = require("../../../js/modules/account.js");
const info = require("../../../js/modules/info.js");
import { forms, storage, util, dialog, api, clickIncrement, clearIncrement } from '../../../js/util';
import BasePage from '../../../js/common/base-page'
import {
  router
} from "../../../js/router";
var app = getApp();
BasePage({
  pageKey: "register",
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    pageType: 1, //1:登录页面  2:注册页面  3:找回密码
    proprietorId:0,
    proprietor:2,
    example: {
      classNames: 'ec-animate--fadeIn',
      enter: true,
      exit: true,
      in: true
    },
    forms: {
      VirtualDir: {
        value: "",
        validate: "isnull",
        error: "邀请码不能为空"
      },
      Name: {
        value: "",
        validate: "isnull",
        error: "请输入您的企业名称"
      },
      Mobile: {
        value: "",
        validate: "isnull|mobile",
        error: "请输入正确的手机号"
      },
      // PicVerifyCode: {
      //   value: "",
      //   validate: "isnull",
      //   error: "请输入正确的图片校验码"
      // },
      ValidateCode: {
        value: "",
        validate: "isnull",
        error: "请输入正确的短信校验码"
      },
      Password: {
        value: "",
        validate: "isnull|pwd",
        error: "请输入正确的密码，密码只能是6~20位英文、数字或者下划线以及点"
      },
      IsAgree:{
        value: false,
        fixed: true,
        validate: "isnull",
        error: "请阅读并同意服务协议和隐私政策"
      }
    },
    current: null,
    role_list: [{
        title: "订货商",
        role: "store"
      },
      {
        title: "供应商",
        role: "supplier"
      }
    ],
    totleHeight: '',
    logo: "",
    bg_pic: "",
    customize: {},
    logoHeight:80,
    mainColor:'',//主题色
    pathUrl:'',
    next:false,
    shadowTitle: '入驻协议'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that=this;
    var role = "store";
    if (options.role) {
      role = options.role;
    }
    that.setData({
      role:role,
      proprietorId: app.dns.proprietorId,
      proprietor: app.dns.proprietor,
      pathUrl: options.type || ''
    });
    this.get_website_config();
    if(app.dns.proprietorId>0){
      that.data.forms.VirtualDir.validate="";
      that.setData({
        forms: that.data.forms
      });
      //获取自定义form表单（名称）
      that.getCustomize();
    }
    //注册的角色
    for (var i in this.data.role_list) {
      var item = this.data.role_list[i];
      if (item.role == role) {
        this.setData({
          current: item
        })
        break;
      }
    }
    // //获得图片验证码组件
    // this.picVerifyCode = this.selectComponent("#picVerifyCode");
    // //设置回调
    // this.picVerifyCode.data.callback = info.getPicVerifyCode;
    // //调用一次图片验证码
    // this.picVerifyCode.bindPicVerifyCode();

    //获得发送短信组件
    this.smsVerifyCode = this.selectComponent("#smsVerifyCode");
    //设置回调
    this.smsVerifyCode.data.callback = this.bindSmsVerifyCode;
    //计算协议高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          totleHeight: res.windowHeight + 'px'
        });
      }
    });
    this.nextCustomize();
  },
  /**
   * 获取自定义表单设置（名称）
   */
  getCustomize:function(){
    let that = this;
    account.register.getCustomize(function(res){
      that.setData({
        customize:res.Content
      })
    })
  },
  /**
   * 表单值绑定
   */
  bindFormValue: function(e) {
    e = e.detail;
    this.data.forms[e.target.id].value = e.detail.value;
  },
  bindValidateVirtualDir(){
    if (this.data.forms.Mobile.value.length>0){
      this.bindValidateUserName();
    }
  },
  /**
   * 校验手机号 
   * */
  bindValidateUserName: function() {
    var that = this;
    // 设置能否发送短信校验码为false
    that.smsVerifyCode.data.isSendSmsCode = false;
    that.data.mobileToken = "";
    that.data.mobileMsg = "";
    var mobile = that.data.forms.Mobile;
    //验证手机号
    if (!forms.validate(mobile)) return false;

    //组装参数
    var param = {
      mobile: mobile.value,
      ProprietorId: app.dns.proprietorId,
      ZoneId: app.dns.zoneId,
      VirtualDir: that.data.forms.VirtualDir.value
    };

    account.register.validateUserName(this.data.current.role,param,
      function(res) {
        if (res.Success) {
          // that.data.mobileToken = res.Content;
          that.setData({
            mobileToken:res.Content
          })
          that.smsVerifyCode.data.isSendSmsCode = false;
        } else {
          //that.smsVerifyCode.data.isSendSmsCode = true;
          that.data.mobileMsg = res.Message;
          that.setData({
            mobileMsg:res.Message
          })
          util.tips(res.Message,3000);
          return;
        }
      });
  },
  /*
  发送短信验证码
   */
  bindSmsVerifyCode: function(callback) {
    var mobile = this.data.mobileToken,
        mobileMsg = this.data.mobileMsg;
    if(mobileMsg!==''){
      util.alert(mobileMsg);
      return;
    };
    if (mobile == undefined || mobile.length == 0) {
      util.alert("手机号未验证成功");
      return;
    }
    // var picvalidatecode = this.data.forms.PicVerifyCode.value;
    // if (picvalidatecode.length == 0) {
    //   util.alert("请先输入4位验证码");
    //   return;
    // }
    // var codeToken = storage.get("pic_verify_code");
    // if (codeToken == undefined || codeToken.length == 0) {
    //   util.alert("图片验证码过期");
    //   return;
    // }

    var data = {
      mobile: mobile,
      verifyCode: '',
      codeToken: '',
      proprietorId: app.dns.proprietorId
    };
    info.sms.getSmsVerifyCode(data, "account." + this.data.current.role+".register.validatecode.get", function (content) {
      if (callback && typeof (callback) == "function") {
        callback(content);
      }
    });
  },
  /**是否同意服务条款 */
  checkboxChange(e) {
    if (this.data.forms.IsAgree.value) {
      this.data.forms.IsAgree.value = false;
    } else {
      this.data.forms.IsAgree.value = true;
    }
    this.setData({ forms: this.data.forms });
  },
  /**加载站点信息 */
  get_website_config() {
    var that = this;
    let { logo, bg_pic, imgDomain } = this.data;
    if (app.dns.proprietorId != app.dns.fkId) return;
    that.setData({
      logo: api.webSite.logo.length > 0 ? api.webSite.logo : logo,
      bg_pic: api.webSite.bgPic.length > 0 ? api.webSite.bgPic : bg_pic,
    });
  },
  /**logo自定义 */
  logoLoad(e){
    if(this.data.logo=='') return;
    var imgwidth = e.detail.width,
        imgheight = e.detail.height;
    var logoHeight = 440*imgheight/imgwidth;
    this.setData({
      logoHeight:logoHeight>200?200:logoHeight
    })
  },
  /*
  注册
   */
  register: function(e) {
    var that = this;
    let {customize,current} = that.data;
    if(current.role=='store'){
      if(customize.Status == 0 || customize.Required != 1){
        that.data.forms.Name.validate = ''
      }else{
        that.data.forms.Name.error = customize.Placeholder;
      }
    }
    
    clickIncrement( ()=> {
      if (that.data.isSubmitOrder) return;
      that.setData({
        isSubmitOrder: true
      });
      account.register.submit(this.data.current.role, that.data.forms,that.data.pathUrl,(s)=>{
        if(s==false){
          that.setData({
            isSubmitOrder: false
          });
        }

      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.setNavigationBarTitle({
      title: api.title
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      mainColor:api.titleColor||"#e56b14"
    })
  },

    /**
   * 获取服务协议
   */
  getProtocol:function(){
    let that = this;
    account.register.getProtocol(this.data.role,function(res){
      let content;
      if(app.dns.proprietor == app.dns.fkFlag){
        content = res
      }else{
        content = res.Content.JoinProtocol;//.replace(/<br\s*\/?>/gi, "\n").replace(/(^\s*)|(\s*$)/g, "\t");
      }
      that.setData({
        shadowTitle:'入驻协议',
        richtext_content: content
      })
      that.showModal();
    })
  },
  /**
   * 获取隐私政策
   */
  getPrivacy:function(){
    let that = this;
    account.register.getPrivacy(function(res){
      that.setData({
        shadowTitle:'隐私政策',
        richtext_content: res
      },()=>{
        that.showModal();
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearIncrement();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 显示遮罩层
   */
  showModal: function (evt) {
    dialog.showModal(this, 'showModalStatus')
  },
  /**
   * 隐藏遮罩层
   */
  hideModal: function () {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
   * 下一步
   */
  nextCustomize(){
    var that = this;
    var param = {
      ProprietorId: app.dns.proprietorId
    };
    account.register.customizeNext(that.data.current.role,param,function(res) {
      if (res.Success) {
        that.setData({
          next:res.Content.length>0
        })
      } 
    });
  },
});